package com.example.figurehecheng.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.example.figurehecheng.common.context.BaseContext;
import com.example.figurehecheng.domain.dto.SceneryCreateDTO;
import com.example.figurehecheng.domain.dto.SceneryUpdateDTO;
import com.example.figurehecheng.domain.entity.Image;
import com.example.figurehecheng.domain.entity.Scenery;
import com.example.figurehecheng.domain.entity.Venues;
import com.example.figurehecheng.domain.vo.SceneryDetailVO;
import com.example.figurehecheng.domain.vo.SceneryVO;
import com.example.figurehecheng.mapper.SceneryMapper;
import com.example.figurehecheng.service.ISceneryService;
import lombok.RequiredArgsConstructor;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.time.LocalDateTime;
import java.util.ArrayList;
import java.util.List;
import java.util.stream.Collectors;

/**
 * <p>
 * 景点表 服务实现类
 * </p>
 *
 * @author author
 * @since 2025-03-04
 */
@Service
@RequiredArgsConstructor
public class SceneryServiceImpl extends ServiceImpl<SceneryMapper, Scenery> implements ISceneryService {
    private final ImageServiceImpl imageServiceImpl;

    @Autowired
    private ISceneryService sceneryService;

    /**
     * 创建景点
     *
     * @param dto
     * @return
     */
    @Override
    public Long createScenery(SceneryCreateDTO dto) {
        // 获取当前商家ID，如果为空则抛出异常
//        Integer currentId = BaseContext.getCurrentId().intValue();
//        if (currentId == null) {
//            throw new RuntimeException("商家未登录");
//        }
        Scenery scenery = new Scenery();
        BeanUtils.copyProperties(dto, scenery);
        // 设置默认值
        scenery.setStatus(1);                    // 默认上架
        scenery.setCreateTime(LocalDateTime.now());
        scenery.setUpdateTime(LocalDateTime.now());
        scenery.setMid(BaseContext.getCurrentId().intValue());    // 设置商家ID
        // 保存并返回ID
        save(scenery);
        return scenery.getId();
    }

    /**
     * 获取商家景点列表
     *
     * @return
     */

    @Override
    public List<SceneryVO> getSceneryListByMid() {
        // 获取当前商家ID
      Integer currentId = BaseContext.getCurrentId().intValue();
        Integer mid = currentId;
        // 构建查询条件
        LambdaQueryWrapper<Scenery> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(Scenery::getMid, mid);

        // 查询数据
        List<Scenery> sceneryList = list(queryWrapper);
        System.out.println(sceneryList);

        // 转换为VO对象
        return sceneryList.stream().map(scenery -> {
            SceneryVO vo = new SceneryVO();
            BeanUtils.copyProperties(scenery, vo);
            return vo;
        }).collect(Collectors.toList());
    }

    /**
     * 获取商家景点详情
     *
     * @return
     */
    @Override
    public SceneryVO getSceneryByMid() {
        // 获取当前商家ID
        Integer currentId = BaseContext.getCurrentId().intValue();
        Integer mid = currentId;
        // 构建查询条件
        LambdaQueryWrapper<Scenery> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(Scenery::getMid, mid);

        // 查询数据
        Scenery scenery = getOne(queryWrapper);

        // 如果未查到数据，返回null
        if (scenery == null) {
            return null;
        }

        // 查询关联的图片列表
        List<Image> images = imageServiceImpl.lambdaQuery()
                .eq(Image::getRelationId, mid)
                .list();

        // 转换为VO对象
        SceneryVO vo = new SceneryVO();
        BeanUtils.copyProperties(scenery, vo);

        // 设置图片列表
        if (images != null && !images.isEmpty()) {
            // 将图片列表转换为图片URL列表
            List<String> imageUrls = images.stream()
                    .map(Image::getUrl)
                    .collect(Collectors.toList());
            vo.setImages(imageUrls);
        }

        return vo;
    }
    /**
     * 修改景点信息
     *
     * @param dto
     * @return
     */
    @Override
    public boolean updateScenery(SceneryUpdateDTO dto) {
        // 获取当前商家ID
        Integer mid = sceneryService.lambdaQuery().one().getMid();
        // 查询原有数据，确认是否属于当前商家
        LambdaQueryWrapper<Scenery> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(Scenery::getId, dto.getId())
                .eq(Scenery::getMid, mid);
        Scenery oldScenery = getOne(queryWrapper);

        if (oldScenery == null) {
            throw new RuntimeException("景点不存在或无权修改");
        }

        // 复制属性并更新
        Scenery scenery = new Scenery();
        BeanUtils.copyProperties(dto, scenery);
//      scenery.setMid(currentId);
        scenery.setUpdateTime(LocalDateTime.now());
        scenery.setStatus(oldScenery.getStatus()); // 保持原有状态

        // 执行更新
        return updateById(scenery);
    }
    /**
     * 获取景点列表
     *
     * @return
     */
    @Override
    public List<SceneryVO> querySceneryList() {
        // 构建查询条件
        LambdaQueryWrapper<Scenery> queryWrapper = new LambdaQueryWrapper<>();

        // 只查询上架的景点
        queryWrapper.eq(Scenery::getStatus, 1);

        // 默认按创建时间降序
        queryWrapper.orderByDesc(Scenery::getCreateTime);

        // 查询数据
        List<Scenery> records = list(queryWrapper);
        List<SceneryVO> result = new ArrayList<>();

        // 转换为VO对象
        for (Scenery scenery : records) {
            SceneryVO vo = new SceneryVO();
            BeanUtils.copyProperties(scenery, vo);

            // 查询景点图片
            List<Image> images = imageServiceImpl.lambdaQuery()
                    .eq(Image::getRelationId, scenery.getId())
                    .list();

            if (images != null && !images.isEmpty()) {
                // 只取第一张图片作为封面
                vo.setCoverImage(images.get(0).getUrl());
            }

            result.add(vo);
        }

        return result;
    }
    /**
     * 获取景点详情
     *
     * @param id
     * @return
     */

    @Override
    public SceneryDetailVO getSceneryDetail(Long id) {
        // 查询景点信息
        Scenery scenery = getById(id);
        if (scenery == null) {
            throw new RuntimeException("景点不存在");
        }

        // 转换为VO
        SceneryDetailVO vo = new SceneryDetailVO();
        BeanUtils.copyProperties(scenery, vo);

        // 查询景点图片
        List<Image> images = imageServiceImpl.lambdaQuery()
                .eq(Image::getRelationId, id)
                .list();

        if (images != null && !images.isEmpty()) {
            List<String> imageUrls = images.stream()
                    .map(Image::getUrl)
                    .collect(Collectors.toList());
            vo.setImages(imageUrls);
        }

        return vo;
    }
    /**
     * 根据名称模糊查询景点列表
     *
     * @param name
     * @return
     */
    @Override
    public List<SceneryVO> getSceneryListByName(String name) {
        LambdaQueryWrapper<Scenery> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.like(Scenery::getName, "%" + name + "%");
        List<Scenery> sceneryList = sceneryService.list(queryWrapper);

        return sceneryList.stream().map(scenery -> {
            SceneryVO vo = new SceneryVO();
            BeanUtils.copyProperties(scenery, vo);
            List<Image> images = imageServiceImpl.lambdaQuery()
                    .eq(Image::getRelationId, scenery.getId())
                    .list();
            if (images != null && !images.isEmpty()) {
                vo.setCoverImage(images.get(0).getUrl());
            }
            return vo;
        }).collect(Collectors.toList());
    }

    /**
     * 计算两点之间的距离（单位：公里）
     */
    private double calculateDistance(double lat1, double lon1, double lat2, double lon2) {
        final int R = 6371; // 地球半径（公里）
        double latDistance = Math.toRadians(lat2 - lat1);
        double lonDistance = Math.toRadians(lon2 - lon1);
        double a = Math.sin(latDistance / 2) * Math.sin(latDistance / 2)
                + Math.cos(Math.toRadians(lat1)) * Math.cos(Math.toRadians(lat2))
                * Math.sin(lonDistance / 2) * Math.sin(lonDistance / 2);
        double c = 2 * Math.atan2(Math.sqrt(a), Math.sqrt(1 - a));
        return R * c;
    }
}
